<template>
  <div :class="styles['editor-container']">
    <!-- 顶部导航 -->
    <div :class="styles['editor-header']">
      <img :src="logoUrl" alt="Logo" :class="styles['logo']" />
      <span :class="styles['separator']">|</span>
      <span :class="styles['navigation']">写文章</span>
    </div>

    <!-- 工具栏 -->
    <div :class="styles['toolbar-full-width']">
      <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
    </div>

    <!-- ✅ 编辑器主体：包含标题、编辑区、表单 -->
    <div :class="styles['editor-main']">
      <!-- 标题栏 -->
      <div :class="styles['title-bar']">
        <div :class="styles['title-input-container']">
          <el-input
            v-model="articleTitle"
            size="large"
            placeholder="请输入文章标题..."
            clearable
            class="title-input"
            maxlength="100"
            show-word-limit
          />
        </div>
      </div>

      <!-- 编辑区域 -->
      <div :class="styles['editor-container-inner']">
        <Editor
          v-model="valueHtml"
          :defaultConfig="editorConfig"
          :mode="mode"
          @onCreated="handleCreated"
        />
      </div>

      <!-- 🔽 表单区域：封面上传、类型选择 -->
      <div :class="styles['form-section']">
        <h3>发布设置</h3>
        <el-form  label-width="auto" style="max-width: 600px">
          <el-form-item label="文章封面：">
            <el-upload
              class="avatar-uploader"
              action="/api/file/uploadCover"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="coverImage" :src="coverImage" class="avatar" alt="封面图"/>
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="文章类型：">
            <el-select v-model="articleType" placeholder="请选择" size="large" style="width: 50%;">
              <el-option
                v-for="item in editorStore.typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- ✅ 固定在视口底部的按钮 -->
    <div :class="styles['fixed-footer']">
      <div :class="styles['footer-content']">
        <!-- 自动保存开关 -->
        <div :class="styles['auto-save-switch']">
          <el-switch
            v-model="autoSaveEnabled"
            active-text="自动保存"
            inactive-text="自动保存"
            inline-prompt
            @change="handleAutoSaveChange"
          />
        </div>
        
        <!-- 保存状态提示 -->
        <div class="save-status">
          <span v-if="editorStore.isAutoSaving" class="saving">保存中...</span>
          <span v-else-if="editorStore.isDirty" class="unsaved">有未保存的更改</span>
          <span v-else class="saved">{{ editorStore.lastSaveTimeFormatted }}</span>
        </div>
        <!-- 字数统计 -->
        <div class="word-count">
          字数：{{ editorStore.wordCount }}
        </div>
        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button size="default" @click="saveDraft" :loading="editorStore.isAutoSaving">
            保存草稿
          </el-button>
          <el-button size="default" type="info" plain @click="previewArticle">
            预览
          </el-button>
          <el-button 
            size="default" 
            type="primary" 
            :disabled="!editorStore.canPublish"
            @click="publishArticle"
          >
            {{ editorStore.editorMode === 'edit' ? '更新文章' : '发布文章' }}
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import '@wangeditor/editor/dist/css/style.css' // 引入富文本编辑器样式
  import { onBeforeUnmount, ref, watch, shallowRef, onMounted, computed } from 'vue'
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
  import { useEditorStore } from '@/stores/modules/editor'
  import { useRoute, useRouter } from 'vue-router'
  import styles from '../../assets/css/editArticle.module.css'
  import zm from '@/utils/zm'
  import type { UploadProps } from 'element-plus'
  import { Plus } from '@element-plus/icons-vue'
  import type { IEditorConfig } from '@wangeditor/editor'

  //=============== 数据 ===============
  const editorStore = useEditorStore()
  const route = useRoute()
  const router = useRouter()
  // 动态导入本地图片
  const logoUrl = new URL('../../assets/images/element-plus-logo.svg', import.meta.url).href
  // 编辑器实例（必须使用 shallowRef）
  const editorRef = shallowRef()
  const mode = 'default'
  // 内容 HTML - 双向绑定到store
  const valueHtml = computed({
    get: () => editorStore.editorHtml,
    set: (value: string) => {
      const textContent = editorRef.value?.getText() || ''
      editorStore.updateContent(value, textContent)
    }
  })
  // 文章标题
  const articleTitle = computed({
    get: () => editorStore.currentArticle.title || '',
    set: (value: string) => editorStore.updateTitle(value)
  })
  // 文章类型
  const articleType = computed({
    get: () =>  editorStore.publishSettings.typeId,
    set: (value: any) => editorStore.updatePublishSettings({ typeId: value })
  })
  // 封面图片
  const coverImage = computed({
    get: () => editorStore.publishSettings.cover,
    set: (value: string) => editorStore.updatePublishSettings({ cover: value })
  })
  // 自动保存开关状态
  const autoSaveEnabled = computed({
    get: () => editorStore.autoSaveEnabled,
    set: (value: boolean) => editorStore.updateAutoSaveSettings(value)
  })
  // 工具栏
  const toolbarConfig = {}
  //编辑器
  const editorConfig: Partial<IEditorConfig> = { 
    placeholder: '请输入内容...',
    // 自动聚焦
    autoFocus: false,
    // 滚动距离
    scroll: true,
    MENU_CONF: {},
  }
  // uploadImage 配置
  if (editorConfig.MENU_CONF) {//确保 MENU_CONF 已正确初始化
    editorConfig.MENU_CONF['uploadImage'] = {
      //接口地址
      server: '/api/file/uploadImage',
      //二进制文件流对应的参数名
      fieldName: 'js-upload-image',
       // 单个文件的最大体积限制，默认为 2M
      maxFileSize: 5 * 1024 * 1024, // 5M
      // 最多可上传几个文件，默认为 100
      maxNumberOfFiles: 20,
      // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
      allowedFileTypes: ['image/*'],
      // 超时时间，默认为 10 秒
      timeout: 10 * 1000, // 10 秒
    }
  }
  
  // 自动保存定时器
  let autoSaveTimer: number | null = null

  //=============== 函数 ===============
  // 编辑器创建完成回调
  const handleCreated = (editor: any) => {
    editorRef.value = editor // 记录实例
    // 设置自动保存
    startAutoSave()
    // 监听内容变化
    editor.on('change', () => {
      const html = editor.getHtml()
      const text = editor.getText()
      editorStore.updateContent(html, text)
    })
  }
  
  // 开始自动保存
  const startAutoSave = () => {
    // 先清除已存在的定时器
    stopAutoSave()
    
    // 只有启用自动保存时才启动定时器
    if (editorStore.autoSaveEnabled) {
      // 默认每60秒自动保存一次
      autoSaveTimer = setInterval(() => {
        editorStore.autoSaveDraft()
      }, 60000)
    }
  }
  
  // 停止自动保存
  const stopAutoSave = () => {
    if (autoSaveTimer) {
      clearInterval(autoSaveTimer)
      autoSaveTimer = null
    }
  }
  
  // 手动保存草稿
  const saveDraft = async () => {
    await editorStore.saveDraft()
  }
  
  // 预览文章
  const previewArticle = () => {
    const previewData = editorStore.getPreviewData()
    // 可以打开新窗口或弹窗显示预览
    console.log('预览数据:', previewData)
    zm.info('预览功能开发中...')
  }
  
  // 发布文章
  const publishArticle = async () => {
    const success = await editorStore.publishArticle()
    if (success) {
      // 发布成功，跳转到文章详情或列表页
      router.push({ name: 'index' })
    }
  }
  
  // 图片上传前验证
  const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const isImage = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(rawFile.type)
    if (!isImage) {
      zm.error('封面图片格式不正确！支持 JPG、PNG、GIF、WebP 格式')
      return false
    }
    if (rawFile.size / 1024 / 1024 > 8) {
      zm.error('封面图片大小不能超过 8MB！')
      return false
    }
    return true
  }
  
  // 图片上传成功
  const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
    // 这里应该使用服务器返回的图片URL，现在暂时使用本地预览
    // const imageUrl = URL.createObjectURL(uploadFile.raw!)
    if(zm.isNotNon(response.data)){
      coverImage.value = response.data
      zm.success('封面上传成功！')
    }else{
      zm.error('封面上传失败')
    }
  }
  
  // 页面离开前提醒
  const beforeUnload = (e: BeforeUnloadEvent) => {
    if (editorStore.isDirty) {
      const message = '请确定已保存后再离开'
      e.returnValue = message
      return message
    }
  }
  
  // 处理自动保存开关变化
  const handleAutoSaveChange = (value: boolean) => {
    // 更新store中的设置
    editorStore.updateAutoSaveSettings(value)
    
    // 根据开关状态启动或停止自动保存
    if (value) {
      startAutoSave()
      zm.info('已开启自动保存，每60秒自动保存一次')
    } else {
      stopAutoSave()
      zm.info('已关闭自动保存')
    }
  }

  //=============== 钩子 ===============
  // 组件挂载后逻辑
  onMounted(async () => {
    // 根据路由参数判断是创建还是编辑模式
    const articleId = route.query.id as string
    
    if (articleId) {
      // 编辑模式
      await editorStore.initEditMode(articleId)
    } else {
      // 创建模式
      editorStore.initCreateMode()
    }
    
    // 添加页面离开提醒
    window.addEventListener('beforeunload', beforeUnload)
  })

  // 组件销毁前：清理资源
  onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor) {
      editor.destroy()
    }
    
    // 停止自动保存
    stopAutoSave()
    
    // 移除页面离开监听
    window.removeEventListener('beforeunload', beforeUnload)
    
    // 如果有未保存的内容，提示保存
    if (editorStore.isDirty) {
      editorStore.autoSaveDraft()
    }
  })

</script>

<style scoped>
/* ✅ 修改标题输入框的提示样式 */
.el-input--large{
  font-size: 24px !important; /* 放大字体 */
  font-weight: bold !important; /* 加粗 */
  color: #c0c4cc !important; /* 可选：调整颜色 */
}

/* ✅ 移除标题栏输入框的边框 */
.title-input :deep(.el-input__wrapper) {
  box-shadow: none !important;
}

.title-input :deep(.el-input__wrapper:hover) {
  box-shadow: none !important;
}

.title-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: none !important;
}

/* 底部操作栏样式 */
.save-status {
  display: flex;
  align-items: center;
  font-size: 12px;
  margin-right: 15px;
}

.save-status .saving {
  color: #409eff;
}

.save-status .unsaved {
  color: #f56c6c;
}

.save-status .saved {
  color: #67c23a;
}

.word-count {
  font-size: 12px;
  color: #909399;
  margin-right: 15px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}
</style>

<style>
/* 封面上传样式，来自element-plus文档 */
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 200px;
  height: 120px;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 120px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar {
  width: 200px;
  height: 120px;
  display: block;
  object-fit: cover; /* 保持比例并填充整个容器 */
  object-position: center; /* 居中显示图片 */
}
</style>